<?php

namespace app\common\model;

use app\common\exception\Exception;
use think\Model;

class UserGroup extends Model
{

    // 表名
    protected $name = 'user_group';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];

    //默认角色
    const GROUP_ADMIN = 1;   //超级管理员
    const GROUP_PICK = 2;   //取件人
    const GROUP_SERVICE = 3;   //维修人

    //默认角色的数组
    const GROUP_IDS = [1,2,3];

    //获取角色列表
    public static function getLists()
    {
        return self::where('status','normal')->order('createtime','desc')->select();
    }

    //角色编辑
    public static function edit($params)
    {
        extract($params);
        //获取包含的子权限 比如角色管理包括：角色编辑，角色删除 ..
        $pull_rules = $rules;
        foreach ($rules as $value){
            $item_rule = UserRule::get($value);
            if ($item_rule->pid > 0) {
                $pull = UserRule::getChildsIds($item_rule->id);
                $pull_rules = array_merge($pull_rules,$pull);
            }
        }
        //id 不存在或为空时添加
        if (!isset($id) || !$id){
            $edit = self::create([
                'name'      => $name,
                'rules'     => join(',',$pull_rules),
                'status'    => 'normal',
            ]);
        }else{
            if (in_array($id,self::GROUP_IDS)){
                new Exception('默认角色不可编辑');
            }
            $edit = self::update([
                'name'      => $name,
                'rules'     => join(',',$pull_rules),
                'status'    => 'normal',
                'id'        => $id
            ]);
        }
        return $edit;
    }

    public static function del($id)
    {
        $row = self::get($id);
        if (!$row){
            new Exception('角色不存在或已被删除');
        }
        if (in_array($id,self::GROUP_IDS)){
            new Exception('默认角色不可删除');
        }
        $user = User::where('FIND_IN_SET('.$id.',group_ids)')->find();
        if ($user){
            new Exception('该角色下存在用户，不可删除');
        }
        return $row->delete();
    }

    //判断用户是否是超级管理员
    public static function isAdmin($user_id)
    {
        $info = User::where('id',$user_id)->where('FIND_IN_SET('.self::GROUP_ADMIN.',group_ids)')->find();
        if (!$info){
            return false;
        }
        return true;
    }

    //判断用户是否是取件人
    public static function isPicker($user_id)
    {
        $info = User::where('id',$user_id)->where('FIND_IN_SET('.self::GROUP_PICK.',group_ids)')->find();
        if (!$info){
            return false;
        }
        return true;
    }

    //判断用户是否是维修人
    public static function isService($user_id)
    {
        $info = User::where('id',$user_id)->where('FIND_IN_SET('.self::GROUP_SERVICE.',group_ids)')->find();
        if (!$info){
            return false;
        }
        return true;
    }
}
